package lm.concurrency.day6.threadpool;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: Min.Liu
 * @Description:
 * @Date: Created in 9:19 2024/11/8
 */
@Slf4j
class Worker extends Thread {
    private final ThreadPool threadPool;
    private Runnable task;

    public Worker(ThreadPool threadPool, Runnable task) {
        this.threadPool = threadPool;
        this.task = task;
    }

    @Override
    public void run() {
        // 执行任务
        // 1) 当 task 不为空，执行任务
        // 2) 当 task 执行完毕，再接着从任务队列获取任务并执行
//            while(task != null || (task = taskQueue.take()) != null) {
        while (task != null || (task = threadPool.getTaskQueue().poll(threadPool.getTimeout(), threadPool.getTimeUnit())) != null) {
            try {
                log.debug("正在执行...{}", task);
                task.run();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                task = null;
            }
        }

        synchronized (threadPool.getWorkers()) {
            log.debug("worker 被移除{}", this);
            threadPool.getWorkers().remove(this);
        }
    }
}
